﻿using System;

namespace Encloser
{
    public static class NumberUtils
    {
        private static readonly Type[] numberTypes = new Type[] { typeof(double), typeof(float), typeof(decimal), typeof(int), typeof(uint), typeof(short), typeof(ushort), typeof(long), typeof(ulong), typeof(byte), typeof(sbyte) };

        public static bool IsNumber(this char ch)
        {
            return ch >= '0' && ch <= '9';
        }

        public static bool IsHex(this char ch)
        {
            return ch >= '0' && ch <= '9' || ch >= 'a' && ch <= 'f' || ch >= 'A' && ch <= 'F';
        }

        public static bool IsNumber(this Type type)
        {
            foreach (var t in numberTypes) if (type == t) return true;
            return false;
        }

        public static bool ParseInt(this string text, out int i, int min = int.MinValue, int max = int.MaxValue)
        {
            i = 0;
            if (string.IsNullOrEmpty(text)) return false;
            try
            {
                i = int.Parse(text);
                if (i < min || i > max) return false;
                return true;
            }
            catch { return false; }
        }

        public static bool ParseLong(this string text, out long i, long min = long.MinValue, long max = long.MaxValue)
        {
            i = 0;
            if (string.IsNullOrEmpty(text)) return false;
            try
            {
                i = long.Parse(text);
                if (i < min || i > max) return false;
                return true;
            }
            catch { return false; }
        }

        public static bool ParseDouble(this string text, out double i, double min = double.MinValue, double max = double.MaxValue)
        {
            i = 0;
            if (string.IsNullOrEmpty(text)) return false;
            try
            {
                i = double.Parse(text);
                if (i < min || i > max) return false;
                return true;
            }
            catch { return false; }
        }
    }
}
